package sf.database.jdbc.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Calendar;

public class CalendarTIMESTAMPType implements TypeHandler<Calendar> {
    public Calendar get(ResultSet rs, String columnName) throws SQLException {
        Timestamp date = rs.getTimestamp(columnName);
        return getCalendar(date);
    }

    public Calendar get(ResultSet rs, int index) throws SQLException {
        Timestamp date = rs.getTimestamp(index);
        return getCalendar(date);
    }

    public Calendar get(CallableStatement rs, int index) throws SQLException {
        Timestamp date = rs.getTimestamp(index);
        return getCalendar(date);
    }

    @Override
    public Calendar get(CallableStatement cs, String parameterName) throws SQLException {
        Timestamp date = cs.getTimestamp(parameterName);
        return getCalendar(date);
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        rs.updateTimestamp(columnLabel, new Timestamp(((Calendar) value).getTimeInMillis()));
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        rs.updateTimestamp(columnIndex, new Timestamp(((Calendar) value).getTimeInMillis()));
    }

    public Object set(PreparedStatement stat, Object obj, int i) throws SQLException {
        if (null == obj) {
            stat.setNull(i, getSqlType());
        } else {
            stat.setTimestamp(i, new Timestamp(((Calendar) obj).getTimeInMillis()));
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object obj, String parameterName) throws SQLException {
        if (null == obj) {
            cs.setNull(parameterName, getSqlType());
        } else {
            cs.setTimestamp(parameterName, new Timestamp(((Calendar) obj).getTimeInMillis()));
        }
        return null;
    }

    @Override
    public int getSqlType() {
        return Types.TIMESTAMP;
    }

    @Override
    public Class<Calendar> getDefaultJavaType() {
        return Calendar.class;
    }

    private static Calendar getCalendar(Timestamp timestamp) {
        if (timestamp != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(timestamp);
            return calendar;
        }
        return null;
    }
}